<style lang="stylus" scoped>
  .h-td-maxwidth
    max-width 150px
</style>

<template>
  <div>
    <q-table
      class="bg-white shadow-1"
      :data="data"
      dense
      :columns="columns"
      row-key="name"
      separator="cell"
      selection="multiple"
      :selected.sync="selected"
      :visible-columns="visibleColumns"
      :pagination.sync="pagination"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-left="props">
        <q-btn size="sm" color="light-blue" :label="$t('新增')" @click="add" />
        <!-- <q-btn color="negative" flat :label="$t('批量删除')" class="q-ml-sm"/> -->
      </template>
      <template v-slot:top-right="props">
        <q-select
          v-model="visibleColumns"
          multiple
          borderless
          options-dense
          :display-value="$t('显示列')"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          class="q-mx-lg"
        >
          <template v-slot:option="scope">
            <q-item
              v-bind="scope.itemProps"
              v-on="scope.itemEvents"
              v-if="!scope.opt.required"
            >
              <q-item-section avatar>
                <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
              </q-item-section>
              <q-item-section style="min-width:60px">
                {{ scope.opt.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-if="searchToggle" v-slot:top-row="props">
        <q-tr :props="props">
          <q-td>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
            <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchForm })"/>
            <q-input dense outlined v-model="searchForm[col.name]" v-else/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-item-label>使用这个租户登录</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="editSpcArgs(props.row.id)">
                  <q-item-section>
                    <q-item-label>特性参数列表</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-item-label>解锁</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup>
                  <q-item-section>
                    <q-item-label>查看资质</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </q-td>
          <q-td key="code" :props="props">
            {{ props.row.code }}
          </q-td>
          <q-td key="name" :props="props">
            {{ props.row.name }}
          </q-td>
          <q-td key="editionName" :props="props">
            <div class="text-pre-wrap">{{ props.row.editionName }}</div>
          </q-td>
          <q-td key="isActive" :props="props">
            <q-chip dense square label="是" color="positive" text-color="white" v-if="props.row.isActive===1"/>
            <q-chip dense square label="否" color="grey" text-color="white" v-if="props.row.isActive===0"/>
          </q-td>
          <q-td key="isApply" :props="props">
            <q-chip dense square label="是" color="positive" text-color="white" v-if="props.row.isApply===1"/>
            <q-chip dense square label="否" color="grey" text-color="white" v-if="props.row.isApply===0"/>
          </q-td>
          <q-td key="isHandle" :props="props" class="h-td-maxwidth ellipsis">
            <q-chip dense square label="是" color="positive" text-color="white" v-if="props.row.isHandle===1"/>
            <q-chip dense square label="否" color="grey" text-color="white" v-if="props.row.isHandle===0"/>
          </q-td>
          <q-td key="isPublish" :props="props">
            <q-chip dense square label="是" color="positive" text-color="white" v-if="props.row.isPublish===1"/>
            <q-chip dense square label="否" color="grey" text-color="white" v-if="props.row.isPublish===0"/>
          </q-td>
          <q-td key="iron" :props="props">{{ props.row.iron }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
            <div class="row justify-between">
              <div class="col-6 q-my-sm">
                <strong class="expand-row-label">创建人：</strong>
                <span>{{ props.row.createUser }}</span>
              </div>
              <div class="col-6 q-my-sm">
                <strong class="expand-row-label">创建时间：</strong>
                <span>{{ props.row.createTime }}</span>
              </div>
              <div class="col-12 q-my-sm">
                <strong class="expand-row-label">说 明：</strong>
                <span>{{ props.row.remark }}</span>
              </div>
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div>租户名称</div>
              <q-input v-model="addOrEditForm.name" dense/>
            </div>
            <div class="col-12">
              <div>管理员邮箱</div>
              <q-input v-model="addOrEditForm.adminEmail" dense/>
            </div>
            <div class="col-12">
              <div>管理员密码</div>
              <q-input v-model="addOrEditForm.adminPassword" dense/>
            </div>
            <div class="col-12">
              <div>版本</div>
              <q-select v-model="addOrEditForm.editionId" :options="versionOptions" emit-value map-options option-value="id" option-label="name" dense/>
            </div>
            <div class="col-12">
              <q-checkbox v-model="addOrEditForm.isLimitSubTime" :true-value="1" :false-value="0" label="限制订购时间" color="light-blue"/>
            </div>
            <div v-if="addOrEditForm.isLimitSubTime === 1" class="col-12">
              <div>订购截止时间</div>
              <el-date-picker
                v-model="addOrEditForm.subEndTime"
                class="el-to-quasar-input-underline"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                default-time="12:00:00">
              </el-date-picker>
            </div>
            <div class="col-12">
              <q-checkbox v-model="addOrEditForm.isTrial" :true-value="1" :false-value="0" label="是否试用" color="light-blue"/>
            </div>
            <div class="col-12">
              <q-checkbox v-model="addOrEditForm.isModifyPassword" :true-value="1" :false-value="0" label="下次登录修改密码" color="light-blue"/>
            </div>
            <div class="col-12">
              <q-checkbox v-model="addOrEditForm.isActiveEmail" :true-value="1" :false-value="0" label="发送激活邮件" color="light-blue"/>
            </div>
            <div class="col-12">
              <q-checkbox v-model="addOrEditForm.isActive" :true-value="1" :false-value="0" label="激活" color="light-blue"/>
            </div>
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" :loading="loadingSave" color="primary" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog
      v-model="spcArgDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>特性参数列表</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="spcArgDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <div :class="$v.userCounts.$error?'text-negative': ''">用户数量上限</div>
          <q-input
            v-model="userCounts"
            :error-message="!$v.userCounts.required?'该字段为必填项':'该字段必须为正整数'"
            :error="$v.userCounts.$error"
            @blur="$v.userCounts.$touch"
            dense hint />
          <q-tree
            color="light-blue"
            :nodes="nodes"
            node-key="label"
            tick-strategy="leaf"
            :ticked.sync="ticked"
            default-expand-all
          >
            <template v-slot:header-input="prop">

            </template>
          </q-tree>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="重置特殊的特性参数" color="primary">
            <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
              <div style="width:150px;font-size:11px">
                重置租户指定的特性参数设置并保存，当前租户只会拥有已注册版本的特性参数
              </div>
            </q-tooltip>
          </q-btn>
          <q-space/>
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators'
import { plusInteger } from 'src/utils/my.validators'
export default {
  name: 'Tenants',
  data () {
    return {
      searchToggle: false,
      searchForm: {
        name: ''
      },
      selected: [],
      visibleColumns: [
        'action',
        'code',
        'name',
        'editionName',
        'isActive',
        'isApply',
        'isHandle',
        'isPublish',
        'iron'
      ],
      columns: [
        { name: 'action', align: 'center', label: '操作' },
        {
          name: 'code',
          required: true, // 当加入此属性时  visibleColumns 对当前字段无效
          label: '租户编码',
          align: 'left',
          field: 'code',
          sortable: true
        },
        { name: 'name', align: 'left', label: '租户名称', field: 'name' },
        { name: 'editionName', label: '版本', align: 'center', field: 'editionName' },
        { name: 'isActive', align: 'center', label: '激活', field: 'isActive' },
        { name: 'isApply', align: 'center', label: '已申请', field: 'isApply' },
        { name: 'isHandle', align: 'center', label: '已处理', field: 'isHandle' },
        { name: 'isPublish', align: 'center', label: '已发布', field: 'isPublish' }
      ],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: ''
      },
      // dialog
      loadingSave: false,
      addOrEdit: 1, // 1 新增  2 修改
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditForm: {
        name: '',
        adminEmail: '',
        adminPassword: '',
        editionId: '',
        isLimitSubTime: 0,
        subEndTime: '',
        isTrial: 0,
        isModifyPassword: 1,
        isActiveEmail: 0,
        isActive: 0
      },
      // 特性参数 dialog
      spcArgDialog: false,
      userCounts: 0,
      nodes: [
        {
          label: '更多参数配置',
          children: [
            {
              label: '特性参数 - 测试1'
            },
            {
              label: '特性参数 - 测试2'
            },
            {
              label: '聊天',
              children: [
                {
                  label: '与其他租户聊天'
                },
                {
                  label: '与宿主聊天'
                }
              ]
            }
          ]
        }
      ],
      ticked: [],
      // options
      versionOptions: []
    }
  },
  validations: {
    addOrEditForm: {

    },
    userCounts: { required, plusInteger }
  },
  computed: {
    pages () {
      return Math.ceil(this.data.length / this.pagination.rowsPerPage)
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    }
  },
  mounted () {
    this.listGet({
      pagination: this.pagination,
      filter: this.searchForm
    })
    this.editionGet()
  },
  methods: {
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/pp/tenant/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    add () {
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        name: '',
        adminEmail: '',
        adminPassword: '',
        editionId: '',
        isLimitSubTime: 0,
        subEndTime: '',
        isTrial: 0,
        isModifyPassword: 1,
        isActiveEmail: 0,
        isActive: 0
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    async edit (row) {
      console.log(this.addOrEditForm)
      await this.$api({
        method: 'get',
        url: `/pp/tenant/findById/${row.id}`,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.addOrEditDialog = true
          this.addOrEditForm = { ...data }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/pp/tenant/add' : '/pp/tenant/update',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除租户：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/pp/tenant/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 特性参数
    editSpcArgs (id) {
      this.spcArgDialog = true
    },
    // 版本数据 获取
    editionGet () {
      this.$api({
        method: 'post',
        url: '/pp/edition/query',
        params: {
          pageNo: 1,
          pageSize: 0
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.versionOptions = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    }
  }
}
</script>
